#include "stdafx.h"
#include "Save.h"
#include "Shlwapi.h"

const CString Save::fileName = "GaiJianSave.ini";

Save::Save(void)
{
}

Save::~Save(void)
{
}

CString Save::getFolder()
{
	CString str;
	//get the path of "My Document"
	SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, str.GetBufferSetLength(100));
	str.ReleaseBuffer();
	//"My Document\GaiJian"
	//str.Append("\\GaiJian");
	return str;
}

CString Save::getPath()
{
	CString path = getFolder() + "\\" + fileName;
	return path;
}

bool Save::isNameExist(CString name)
{
	CStringArray strArray;
	getNames(&strArray);
	for(int i = 0; i < strArray.GetSize(); i++)
	{
		if(strArray[i] == name)
			return true;
	}
	return false;
}

void Save::addName(CString name) 
{
	if(isNameExist(name))
		return;
	WritePrivateProfileSection(name, "", getPath());
}

bool Save::getNames(CStringArray* strArray)
{
	char str[500];
	GetPrivateProfileSectionNames(str, 500, getPath());
	if(str[0] == NULL)
		return false;
	// Split the section
	CString strTemp;
	for(int i = 0; i < 500; i++)
	{
		if(str[i] == NULL)
		{
			if(i-1 >= 0)
				if(str[i-1] == NULL)
					break;
			strArray->Add(strTemp);
			strTemp.Empty();
		}
		else
		{
			strTemp.AppendChar(str[i]);
		}
	}
	return true;
}

MapKeys Save::getMapKeys(CString name)
{
	CString strSplit, key[2];
	char str[500];
	MapKeys mapKeys;
	GetPrivateProfileSection(name, str, 500, getPath());
	if(str[0] == NULL)
		return mapKeys;
	// Split the section
	CStringArray strArray;
	CString strTemp;
	for(int i = 0; i < 500; i++)
	{
		if(str[i] == NULL)
		{
			if(i-1 >= 0)
				if(str[i-1] == NULL)
					break;
			strArray.Add(strTemp);
			strTemp.Empty();
		}
		else
		{
			strTemp.AppendChar(str[i]);
		}
	}
	//strArray to Map
	for(int i = 0; i < strArray.GetCount(); i++)
	{
		for(int start = 0, j = 0; start < strArray[i].GetLength();j++)
		{
			key[j] = strArray[i].Tokenize("=", start);
		}
		mapKeys.insert(pair<int, int>(atoi(key[0]), atoi(key[1])));
	}
	return mapKeys;
}

void Save::insert(CString appName, int key, int value)
{
	CString key1, key2;
	key1.Format("%d", key);
	key2.Format("%d", value);
	WritePrivateProfileString(appName, key1, key2, getPath());
}

void Save::del(CString appName)
{
	WritePrivateProfileSection(appName, NULL, getPath());
}

void Save::del(CString appName, int key) 
{
	CString strKey;
	strKey.Format("%d", key);
	WritePrivateProfileString(appName, strKey, NULL, getPath());

}